package com.cloud.message;

import com.cloud.utils.JSONUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.nio.charset.Charset;

/**
 * 消息生成器
 *
 * @author yzj
 */
public class MQMessageBuilder {

    /**
     * 消息延迟数组变量
     */
    private final String[] DELAY_ARRAY = "1s,5s,10s,30s,1m,2m,3m,4m,5m,6m,7m,8m,9m,10m,20m,30m,1h,2h".split(",");
    /**
     * 消息主题
     */
    private String topic;
    /**
     * 消息标记
     */
    private String tag;
    /**
     * 消息内容
     */
    private Object message;
    /**
     * 消息key
     */
    private String key;
    /**
     * 消息延迟等级
     */
    private Integer level;

    public static MQMessageBuilder message(String topic, String tag, Object message, String key) {
        MQMessageBuilder builder = new MQMessageBuilder();
        builder.setTopic(topic);
        builder.setTag(tag);
        builder.setMessage(message);
        builder.setKey(key);
        return builder;
    }

    public static MQMessageBuilder message(String topic, String tag, Object message, String key, DelayLevel level) {
        MQMessageBuilder builder = new MQMessageBuilder();
        builder.setTopic(topic);
        builder.setTag(tag);
        builder.setMessage(message);
        builder.setKey(key);
        builder.setLevel(level.getLevel());
        return builder;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public Object getMessage() {
        return message;
    }

    public void setMessage(Object message) {
        this.message = message;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public Message build() {
        if (StringUtils.isEmpty(this.topic)) {
            throw new RuntimeException("未定义发送此消息的主题");
        }
        if (StringUtils.isEmpty(this.key)) {
            throw new RuntimeException("未定义用于发送此消息的消息键");
        }
        if (ObjectUtils.isEmpty(this.message)) {
            throw new RuntimeException("消息正文不能为空");
        }
        String str = JSONUtils.toJson(this.message);
        Message message = new Message(this.topic, str.getBytes(Charset.forName(RemotingHelper.DEFAULT_CHARSET)));
        if (!StringUtils.isEmpty(this.tag)) {
            message.setTags(this.tag);
        }
        message.setKeys(this.key);
        if (this.level != null && this.level > 0 && this.level <= DELAY_ARRAY.length) {
            message.setDelayTimeLevel(this.level);
        }
        return message;
    }

}
